<script lang="ts" setup>
import { getToken } from '@/utils/cache/cookies'
import { DateModelType, ElMessage, FormInstance, FormRules } from 'element-plus'
import { reactive, ref } from 'vue'
import CustomActiveButtonGroup from '@/components/basic/ui-elements/CustomActiveButtonGroup.vue'
import CustomActiveButton from '@/components/basic/ui-elements/CustomActiveButton.vue'
import { sendCoupon } from '@/api/user'
import { sendCouponRequestData } from '@/api/user/types/user'
import dayjs, { OpUnitType } from 'dayjs'
const dialogVisible = ref(false)
const form = reactive<sendCouponRequestData>({
  couponType: '4',
  count: 1,
  discountAmount: '',
  minOrderAmount: '0',
  startDate: '',
  endDate: '',
  userId: '',
  coupon: '抵扣'
})
const emits = defineEmits(['refresh'])
const formRef = ref<FormInstance | null>(null)
type ModelDateType = string | number | Date | [DateModelType, DateModelType]
const time = ref<ModelDateType>('')
const rules = reactive<FormRules>({
  couponType: [
    {
      required: true,
      message: '请选择优惠券类型',
      trigger: 'blur'
    }
  ],
  discountAmount: [
    {
      required: true,
      message: '卡券金额必填',
      trigger: ['blur', 'change']
    }
  ],
  minOrderAmount: [
    {
      required: true,
      message: '门槛金额必填',
      trigger: 'blur'
    }
  ],
  count: [
    {
      required: true,
      message: '赠送数量必填',
      trigger: 'blur'
    }
  ]
})
const handleDateChange = (value: string[] | string) => {
  if (value && value.length === 2) {
    form.startDate = value[0]
    form.endDate = value[1]
  } else {
    form.startDate = dayjs(value as string)
      .startOf(time.value as OpUnitType)
      .format('YYYY-MM-DD HH:mm:ss')
    form.endDate = dayjs(value as string)
      .endOf(time.value as OpUnitType)
      .format('YYYY-MM-DD HH:mm:ss')
  }
}
const reset = () => {
  dialogVisible.value = false
}
const handleClose = () => {
  formRef.value?.resetFields()
  time.value = ''
}
const submit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      sendCoupon({
        token: getToken() ?? '',
        ...form
      })
        .then((res) => {
          if (res.statusCode === '0') {
            dialogVisible.value = false
            ElMessage.success(res.data)
            emits('refresh')
          } else {
            formRef.value?.resetFields()
          }
        })
        .catch((error) => {
          console.error(error)
        })
    }
  })
}
const open = () => {
  dialogVisible.value = true
}
const setId = (userId: string) => {
  form.userId = userId
}
defineExpose({ open, setId })
</script>

<template>
  <el-dialog v-model="dialogVisible" title="赠送优惠券" width="500px" @close="handleClose" center>
    <el-form :model="form" :rules="rules" ref="formRef" label-position="top">
      <el-form-item prop="couponType" label="优惠类型">
        <custom-active-button-group v-model="form.couponType">
          <custom-active-button active-value="4" inactive-value="">短租</custom-active-button>
          <custom-active-button active-value="3" inactive-value="">长租</custom-active-button>
        </custom-active-button-group>
      </el-form-item>
      <el-form-item label="优惠券类型">
        <custom-active-button-group v-model="form.coupon">
          <custom-active-button active-value="抵扣" inactive-value="">抵扣券</custom-active-button>
          <custom-active-button active-value="时长" inactive-value="" :disabled="true"
            >时长券</custom-active-button
          >
        </custom-active-button-group>
      </el-form-item>
      <el-form-item prop="discountAmount" label="卡券">
        <custom-active-button-group v-model="form.discountAmount" v-if="form.couponType === '4'">
          <custom-active-button active-value="1" inactive-value="">1元</custom-active-button>
          <custom-active-button active-value="2" inactive-value="">2元</custom-active-button>
          <custom-active-button active-value="2.5" inactive-value="">2.5元</custom-active-button>
          <custom-active-button active-value="5" inactive-value="">5元</custom-active-button>
          <el-input
            v-model="form.discountAmount"
            type="text"
            :formatter="(value: string) => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="(value: string) => value.replace(/\￥\s?|(,*)/g, '')"
            placeholder="自定义"
            class="custom-input"
          />
        </custom-active-button-group>
        <template v-else>
          <div grid grid-cols-2 grid-row-1 gap-x-20>
            <el-input v-model="form.minOrderAmount" placeholder="请输入">
              <template #prepend>满</template>
            </el-input>
            <el-input v-model="form.discountAmount" placeholder="请输入">
              <template #prepend>减</template>
            </el-input>
          </div>
        </template>
      </el-form-item>
      <el-form-item label="卡券时间">
        <el-date-picker
          v-model="time"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          @change="handleDateChange"
        />
      </el-form-item>
      <el-form-item prop="count" label="赠送数量">
        <el-input-number v-model="form.count" :min="1" :max="50" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button plain @click="reset">取消</el-button>
      <el-button type="primary" @click="submit">发送</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.custom-input {
  width: 70px;
}
</style>
